<template>
  <div>
    <h1>广告位信息</h1>
    <el-row>
      <el-col :span="20" :push='2'>
        <div>
          <el-form :inline="true">
            <el-form-item style="float: left" label="查询广告位信息:">
              <el-input v-model="search" placeholder="查询所需要的内容......"></el-input>
            </el-form-item>
            <el-form-item style="float: right">
              <el-button v-if="role==='manager'" type="primary" size="small" icon="el-icon-edit-outline"
                         @click="handleAdd">添加
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <el-table
            :data=tables.slice((page-1)*pageSize,page*pageSize)
            border
            style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="60">
            </el-table-column>
            <el-table-column
              label="编号"
              align="center"
              width="220">
              <template slot-scope="scope">
                <span>{{scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="类型"
              align="center"
              width="220">
              <template slot-scope="scope">
                <span>{{scope.row.spotType}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="规格"
              align="center"
              width="220">
              <template slot-scope="scope">
                <span>{{scope.row.spotSize}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="图片"
              align="center"
              width="120">
              <template slot-scope="scope">
                <el-button type="text" @click="showImage(scope.row.imageSrc)">查看</el-button>
                <el-dialog title="预览图片" :visible.sync="dialogTableVisible">
                  <img style="width: 100%; height: 100%" :src="imageSrc">
                </el-dialog>
              </template>
            </el-table-column>
            <el-table-column
              label="所在小区"
              align="center"
              width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.communityName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="档期"
              align="center"
              width="165">
              <template slot-scope="scope">
                <router-link :to="{name: 'schedule', params: { spotId: scope.row.id}}">
                  <el-link type="primary" :underline="false">查看</el-link>
                </router-link>
              </template>
            </el-table-column>
            <el-table-column
              label="状态"
              align="center"
              width="160">
              <template slot-scope="scope">
                <span v-if="scope.row.isBusy===false && scope.row.isRepair===false">空闲</span>
                <span v-if="scope.row.isBusy===true && scope.row.isRepair===false">使用中</span>
                <span v-if="scope.row.isRepair===true">维修中</span>
              </template>
            </el-table-column>
            <el-table-column v-if="role==='customer'" label="用户操作" align="center" width="160">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" v-if="scope.row.isRepair===false"
                           @click="handleBook(scope.row)" >预定
                </el-button>
                <el-button size="mini" type="primary" v-if="scope.row.isRepair===true"
                           disabled >预定
                </el-button>
                <el-button
                  size="mini"
                  type="warning"
                  @click="handleError(scope.row)"
                  v-if="scope.row.isRepair===false">报障
                </el-button>
                <el-button
                  size="mini"
                  type="warning"
                  disabled
                  v-if="scope.row.isRepair===true">报障
                </el-button>
              </template>
            </el-table-column>
            <el-table-column v-if="role==='manager' && isLogin==='true'" label="管理员操作" align="center" width="160">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24" class="el-table_footstool">
            <el-pagination layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                           @current-change="handleCurrentChange" :page-sizes="[10, 15]" :page-size="pageSize"
                           :total="tables.length" style="float:right;">
            </el-pagination>
          </el-col>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-dialog
        title="广告位预定"
        :visible.sync="centerDialogVisible"
        width="40%"
        center>
        <el-form :model="dateList" style="padding-left: 100px">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleBookResult()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <addSpot :dialogAdd="dialogAdd" @update="getSpotsInfo"></addSpot>
  </div>
</template>

<script>
import addSpot from './addSpot.vue'
import spotApi from '@/api/spot/spot'

export default {
  name: 'spotList',
  data () {
    return {
      pickerOptions: {// 日期选择器禁用选择
        disabledDate: (time) => {
          return this.dealDisabledDate(time)
        }
      },
      imageSrc: '',
      dateList: {}, // 时间选择器:model需要
      flagList: {},
      date: [], // 时间选择器的时间数组
      dialogAdd: {// 广告位添加弹窗控制
        show: false
      },
      isLogin: this.$store.state.isLogin, // 用户是否登录
      role: this.$store.state.role, // 用户角色
      accountId: this.$store.state.accountId, // 账号的id
      dialogTableVisible: // 图片查看弹窗控制
        false,
      centerDialogVisible: // 广告位预订弹窗控制
        false,
      spot: // 广告位对象
        {
          communityId: '',
          communityName: '',
          isBusy: '',
          isRepair: '',
          id: '',
          type: '',
          size: '',
          image: '',
          schedule: []
        },
      bookVo: {// 预订广告位对象
        customerId: this.$store.state.accountId,
        endDate: '',
        spotId: '',
        startDate: ''
      },
      maintenanceVo: {// 广告位维修对象
        customerId: this.$store.state.accountId,
        spotId: ''
      },
      spotList: [], // 广告位列表
      search: // 搜索框是否有数据
        '',
      page: // 页码
        1,
      pageSize: // 页数
        10
    }
  },
  /**
   * @description 对广告位列表进行搜索
   */
  computed: {
    // 模糊搜索
    tables () {
      const search = this.search
      if (search) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素
        return this.spotList.filter(data => {
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            return String(data[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.spotList
    }
  },

  methods: {
    /**
     *@description 显示广告位图片
     * @param image 图片路径
     */
    showImage (image) {
      this.imageSrc = ''
      this.dialogTableVisible = true
      this.imageSrc = image
    },
    /**
     * 广告位预订取消
     */
    handleCancel () {
      this.centerDialogVisible = false
    },
    /**
     * @description 获取广告位列表
     */
    getSpotsInfo () {
      spotApi.getSpotList().then(res => {
        this.spotList = res.data
      })
    },
    /**
     * @description 客户进行广告位预订
     * @param data
     */
    handleBook (data) {
      this.getDate(data.id)
      this.centerDialogVisible = true
      // 填充bookVo
      this.bookVo.spotId = data.id
    },
    /***
     * @description 用户进项广告位预订时,日期选择器的禁选日期设置
     * @param time
     * @returns {boolean}
     */
    dealDisabledDate (time) {
      if (this.dateList === null) {
        return time.getTime() < Date.now()
      } else {
        let flag = time.getTime() < Date.now()
        for (let item of this.dateList) {
          let start = item.startDate.split('-')
          let end = item.endDate.split('-')
          flag = flag || (time.getTime() < new Date(end[0], end[1] - 1, Number(end[2]) + 1) && time.getTime() > new Date(start[0], start[1] - 1, Number(start[2]) - 1))
        }
        return flag
      }
    },
    /**
     * @description 用户预订
     */
    handleBookResult () {
      this.centerDialogVisible = false
      // 提交到预定订单
      this.bookVo.startDate = this.date[0]
      this.bookVo.endDate = this.date[1]
      spotApi.bookSpot(this.bookVo).then(data => {
        this.$message({
          type: 'success',
          message: '预定成功'
        })
        this.getSpotsInfo() // 删除数据，更新视图
      }).catch(err => {
        this.$message({
          type: 'warning',
          message: '预定失败'
        })
        console.log(err)
      }
      )
    },
    /**
     * @description 用户保障
     * @param data
     */
    handleError (data) {
      // 报障
      // 提交到数据库改变状态
      this.maintenanceVo.spotId = data.id
      spotApi.reportError(this.maintenanceVo).then(data => {
        console.log(data)
        this.$message({
          type: 'success',
          message: '报障成功'
        })
        this.getSpotsInfo() // 删除数据，更新视图
      }).catch(err => {
        this.$message({
          type: 'warning',
          message: '报障失败'
        })
        console.log(err)
      }
      )
    },
    /**
     * @description 管理员广告位删除
     * @param index
     * @param row
     */
    handleDelete (index, row) {
      spotApi.deleteSpot(row.id).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getSpotsInfo()
        this.page = 1
      })
    },
    /**
     * @description 管理员广告位添加
     */
    handleAdd () {
      this.dialogAdd.show = true
    },
    // 初始页page、初始每页数据数pageSize和数据data
    handleSizeChange (size) {
      this.pageSize = size
    },
    handleCurrentChange (val) {
      this.page = val
    },
    getDate (spotId) {
      spotApi.getDate(spotId).then(res => {
        this.dateList = res.data
      })
    }
  },

  /**
   * @description 初始化页面显示广告位列表
   */
  mounted () {
    this.getSpotsInfo()
  },
  components: {
    addSpot
  }
}
</script>

<style scoped>

</style>
